#include "stdafx.h" 
#include "detours.h" 
#include "winsock2.h" 
#include "stdio.h" 

static int   (WINAPI * TrueConnect)(SOCKET s, const struct sockaddr FAR *name, int namelen) = connect;

static int  (WINAPI * TrueWSARecv)(SOCKET s,LPWSABUF lpBuffers,DWORD dwBufferCount,LPDWORD lpNumberOfBytesRecvd,LPDWORD lpFlags,LPWSAOVERLAPPED lpOverlapped,LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) = WSARecv; 

static int  (WINAPI * TrueWSASend)(SOCKET s,LPWSABUF lpBuffers,DWORD dwBufferCount,LPDWORD lpNumberOfBytesSent,DWORD dwFlags,LPWSAOVERLAPPED lpOverlapped,LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)=WSASend; 


__declspec(dllexport)  void WINAPI NewConnect(SOCKET s, const struct sockaddr FAR *name, int namelen) 
{ 
	char    buf[128]={0}; 
	SOCKADDR_IN * saServer = (struct sockaddr_in *)name;    
	sprintf(buf, "IP=%s Port=%d",::inet_ntoa(saServer->sin_addr),::ntohs(saServer->sin_port)); 
	//MessageBox(NULL,buf,"connect hooked",NULL); 
	TrueConnect(s, name, namelen); 
} 


int WINAPI NewWSARecv(SOCKET s,LPWSABUF lpBuffers,DWORD dwBufferCount,LPDWORD lpNumberOfBytesRecvd,LPDWORD lpFlags,LPWSAOVERLAPPED lpOverlapped,LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) 
{ 
	DWORD  nRead;  

	//TrueWSARecv(s,lpBuffers,dwBufferCount,lpNumberOfBytesRecvd,lpFlags,lpOverlapped,lpCompletionRoutine); 
	int ret; 
	ret = TrueWSARecv(s,lpBuffers,dwBufferCount,lpNumberOfBytesRecvd,lpFlags,lpOverlapped,lpCompletionRoutine); 

	//MessageBox(NULL,lpBuffers->buf,"wsarecv hooked",NULL); 

	char buf[1024]={0}; 
	strcpy(buf,lpBuffers->buf); 
	
	return ret; 


} 
void WINAPI NewWSASend(SOCKET s,LPWSABUF lpBuffers,DWORD dwBufferCount,LPDWORD lpNumberOfBytesSent,DWORD dwFlags,LPWSAOVERLAPPED lpOverlapped,LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) 
{ 
	//MessageBox(NULL,"wsarsend","wsasend hooked",NULL); 
	TrueWSASend(s,lpBuffers,dwBufferCount,lpNumberOfBytesSent,dwFlags,lpOverlapped,lpCompletionRoutine); 
} 


BOOL APIENTRY DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved) 
{ 
	if (dwReason == DLL_PROCESS_ATTACH) { 
		DetourTransactionBegin(); 
		DetourUpdateThread(GetCurrentThread()); 

		DetourAttach(&(PVOID&)TrueConnect, NewConnect); 

		DetourAttach(&(PVOID&)TrueWSARecv, NewWSARecv); 
		DetourAttach(&(PVOID&)TrueWSASend, NewWSASend); 
		DetourTransactionCommit(); 
		DetourRestoreAfterWith(); 

	} 
	else if (dwReason == DLL_PROCESS_DETACH) { 
		DetourTransactionBegin(); 
		DetourUpdateThread(GetCurrentThread()); 

		DetourDetach(&(PVOID&)TrueConnect, NewConnect); 

		DetourDetach(&(PVOID&)TrueWSARecv, NewWSARecv); 
		DetourDetach(&(PVOID&)TrueWSASend, TrueWSASend); 
		DetourTransactionCommit(); 
	} 
	return TRUE; 
}

